#include "audiohandler.h"

// 发送端
AudioSender::AudioSender(QString ip, int port, QObject *parent)
    : QObject(parent), ip(ip), port(port) {
    socket = new QUdpSocket(this);

    // 音频格式设置（精简参数）
    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    if (!info.isFormatSupported(format)) {
        qWarning() << "不支持默认格式，正在尝试最近的格式";
        format = info.nearestFormat(format);
    }

    audioInput = new QAudioInput(format, this);
    inputDevice = audioInput->start();  // 获取输入设备
}

void AudioSender::start()
{
    connect(inputDevice, &QIODevice::readyRead, [this]() {
        QByteArray data = inputDevice->readAll();  // 从音频设备读取数据
        if (!data.isEmpty()) {
            socket->writeDatagram(data, QHostAddress(ip), port);
        }
    });
}
//void AudioSender::start() {
//    audioInput->start(socket); // 直接写入UDP Socket发送
//    connect(socket, &QUdpSocket::readyRead, [this]() {
//        QByteArray data = socket->readAll();
//        socket->writeDatagram(data, QHostAddress(ip), port);
//    });
//}

// 接收端
AudioRecver::AudioRecver(QString ip, int port, QObject *parent)
    : QObject(parent) {
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ReuseAddressHint);
    socket->joinMulticastGroup(QHostAddress(ip));

    // 音频格式需与发送端一致
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    // 检查输出格式
       QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
       if (!info.isFormatSupported(format)) {
           qWarning() << "Raw audio format not supported, trying nearest...";
           format = info.nearestFormat(format);
       }

    audioOutput = new QAudioOutput(format, this);
    outputDevice = audioOutput->start();
}

void AudioRecver::start() {
    connect(socket, &QUdpSocket::readyRead, [this]() {
        while (socket->hasPendingDatagrams()) {
            QByteArray data;
            data.resize(socket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;
            socket->readDatagram(data.data(), data.size(), &sender, &senderPort);

            if (outputDevice->isWritable() && data.size() > 0) {
                outputDevice->write(data);
            }
        }
    });
}

//void AudioRecver::start() {
//    connect(socket, &QUdpSocket::readyRead, [this]() {
//        while (socket->hasPendingDatagrams()) {
//            QByteArray data;
//            data.resize(socket->pendingDatagramSize());
//            socket->readDatagram(data.data(), data.size());
//            outputDevice->write(data); // 直接播放
//        }
//    });
//}
//#include "audiohandler.h"

//audiohandler::audiohandler(QObject *parent) : QObject(parent)
//{

//}
